from flask import request
from flask_restx import fields, Resource
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from .. import db
from ..models import User
from . import make_namespace
from ..core import make_response


api = make_namespace("01.Auth", "认证与授权")


user_login_model = api.model("UserLogin", {
	"username": fields.String(required=True),
	"password": fields.String(required=True),
})

user_register_model = api.model("UserRegister", {
	"username": fields.String(required=True),
	"email": fields.String(required=True),
	"password": fields.String(required=True),
})

token_pair_model = api.model("TokenPair", {
	"access_token": fields.String,
	"refresh_token": fields.String,
})

reset_password_model = api.model("ResetPassword", {
	"email": fields.String(required=True),
	"new_password": fields.String(required=True),
})


@api.route("/register")
class Register(Resource):
	@api.expect(user_register_model, validate=True)
	def post(self):
		payload = request.get_json()
		username = payload["username"].strip()
		email = payload["email"].strip().lower()
		password = payload["password"]

		if User.query.filter((User.username == username) | (User.email == email)).first():
			return make_response(code=400, msg="用户名或邮箱已存在", data=None)

		user = User(username=username, email=email)
		user.set_password(password)
		db.session.add(user)
		db.session.commit()

		access = create_access_token(identity=str(user.id))
		refresh = create_refresh_token(identity=str(user.id))
		return make_response({"access_token": access, "refresh_token": refresh})


@api.route("/login")
class Login(Resource):
	@api.expect(user_login_model, validate=True)
	def post(self):
		payload = request.get_json()
		username = payload.get("username", "").strip()
		password = payload.get("password", "")

		user = User.query.filter((User.username == username) | (User.email == username.lower())).first()
		if not user or not user.check_password(password):
			return make_response(code=401, msg="用户名或密码错误", data=None)

		# 禁止停用用户登录
		from ..models.user import UserStatus
		if user.status == UserStatus.deactivate:
			return make_response(code=403, msg="用户已被停用", data=None)

		access = create_access_token(identity=str(user.id))
		refresh = create_refresh_token(identity=str(user.id))
		return make_response({"access_token": access, "refresh_token": refresh})


@api.route("/refresh")
class Refresh(Resource):
	@jwt_required(refresh=True)
	def post(self):
		user_id = get_jwt_identity()
		access = create_access_token(identity=user_id)
		return make_response({"access_token": access, "refresh_token": None})


@api.route("/reset-password")
class ResetPassword(Resource):
	@api.expect(reset_password_model, validate=True)
	def post(self):
		payload = request.get_json()
		email = payload["email"].strip().lower()
		new_password = payload["new_password"]
		user = User.query.filter_by(email=email).first()
		if not user:
			return make_response(code=404, msg="用户不存在", data=None)
		user.set_password(new_password)
		db.session.commit()
		return make_response({"message": "密码已重置"})


